package com.leetroll.media.job;

import com.leetroll.api.service.ItemService;
import com.leetroll.common.entity.Item;
import com.leetroll.common.enums.EFileType;
import com.leetroll.common.enums.EItemType;
import com.leetroll.media.service.JobExecutor;
import com.leetroll.media.service.UpDownloadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.concurrent.ExecutionException;

@Service
@Slf4j
public class Job_Bluezone {

    private final ItemService itemService;
    private final UpDownloadService upDownloadService;
    private JobExecutor jobExecutor;

    public Job_Bluezone(ItemService itemService, UpDownloadService upDownloadService, JobExecutor jobExecutor) {
        this.itemService = itemService;
        this.upDownloadService = upDownloadService;
        this.jobExecutor = jobExecutor;
    }

    public void upload() throws ExecutionException, InterruptedException {
        File folder = new File("F:\\_resources\\sound\\Video Presets - 1950+ Cinematic Sound Effects [For Filmmakers]");
        if (!folder.exists() || !folder.isDirectory()) return;

        File[] soundFolders = folder.listFiles();
        if (soundFolders == null) return;

        for (File soundFolder : soundFolders) {
            if (!soundFolder.isDirectory()) continue;
            jobExecutor.submit(() -> uploadItem(soundFolder));
        }
        jobExecutor.await();
        log.info("finished...");

    }

    private Object uploadItem(File folder) {
        log.info("----------------------准备插入 item[{}]----------------------", folder.getName());
//        if (folder.isDirectory()) return 0;

        File[] files = folder.listFiles();
        if (files == null) return 1;

        //插入item表
        String name = folder.getName().split("\\.")[0];
        String replaced = name.replace(",", " ");

        for (File file : files) {
            if (file.isDirectory()) {
                uploadItem(file);
                continue;
            }
            Item item = new Item();
            item.setName(file.getName().split("\\.")[0]);
            item.setAlias(file.getName().split("\\.")[0]);
            item.setCatId(5L);
            item.setStatus("show");
            item.setSource("Filmmakers");
            item.setAuthor("Joseph");
            item.setPrice(0.0);
            item.setMark("");
            item.setType(EItemType.SOUND.getType());
            item.setDesp(replaced);
            item.setTag("action");
            item.setCreateTime(new Date());
            item.setUpdateTime(new Date());
            itemService.save(item);

            //插入主图文件
            upDownloadService.upload2AliByType(item.getId(), file, EFileType.MAIN);
            log.info("\t\t\t>> 音效插入成功 {}", file.getAbsolutePath());
        }

        return 1;
    }
}
